package ar.fiuba.tp7552.buildadmin.service.impl;

import java.util.Collection;

import org.springframework.transaction.annotation.Transactional;

import ar.fiuba.tp7552.buildadmin.dao.UserDao;
import ar.fiuba.tp7552.buildadmin.model.BaseEntity;
import ar.fiuba.tp7552.buildadmin.model.BusinessException;
import ar.fiuba.tp7552.buildadmin.model.auth.User;
import ar.fiuba.tp7552.buildadmin.service.PermissionService;
import ar.fiuba.tp7552.buildadmin.service.PermissionType;
import ar.fiuba.tp7552.buildadmin.service.UserService;

@Transactional
public class UserServiceImpl implements UserService {

	private UserDao userDao;
	private PermissionService permissionService;
	
	public UserServiceImpl(UserDao dao, PermissionService service) {
		super();
		this.userDao = dao;
		this.permissionService = service;
	}

	@Override
	public void createUser(User user) throws BusinessException {
		String username = user.getUsername();
		User other = userDao.findByUsername(username);
		if (other != null) {
			throw new BusinessException("Ya existe una cuenta de usuario asignada a "+username);
		} else {
			userDao.save(user);
		}
	}

	@Override
	public User getUser(Long userId) {
		return userDao.get(userId);
	}

	@Override
	public void deleteUser(Long userId) {
		permissionService.deletePermissions(userDao.get(userId));
		userDao.remove(userId);
		
	}

	@Override
	public Collection<User> getAll() {
		return userDao.getAll();
	}

	@Override
	public void addPermission(User user, BaseEntity entity, PermissionType permission) {
//		permissionService.addPermission(entity, user, permission.getPermission());
	}

	@Override
	public void delPermission(User user, BaseEntity entity, PermissionType permission) {
		// TODO borrar permisos.
	}
	
	@Transactional
	public void update(User user) {
		userDao.update(user);
	}

}
